<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>报价</title>
    <link rel="stylesheet" href="plugins/layui/css/layui.css"/>
    <!-- <link rel="stylesheet" href="css/comments.css"> -->
    <link rel="stylesheet" href="css/goods.css">
    <style>
		.maincontainer {
		    padding: 10px;
		}
        .layui-form-label{
            width: 150px;
        }
        .layui-input-block{
            margin-left: 180px;
        }
        .pre_table{
            display: none;
        }
    </style>
</head>
<style>
</style>
<body>
<div class="maincontainer">
    <blockquote class="layui-elem-quote">
        报价
        <button type="button" class="layui-btn layui-btn-sm" style="float: right;margin-top: -4px;" onclick="window.history.back();">返回</button>
    </blockquote>
    <div class="all-info">
		<form class="layui-form" action="">
            <div class="layui-form-item">
			 	<label class="layui-form-label mainImagelabel">商品主图：</label>
			 	<div class="layui-input-inline">
			 		<div class="imgList">
			 			<ul class="mainpicture">
			 				<li class="nullimg mainImg">
			 					<div>
			 						<i class="layui-icon layui-icon-upload"></i>
			 						<p>上传商品主图</p>
			 					</div>
			 				</li>
			 				<li class="showMImg" style="display: none">

			 				</li>
			 			</ul>
			 		</div>
			 	</div>
            </div>
			<div class="layui-form-item">
			  <label class="layui-form-label namelabel">商品名称：</label>
			  <div class="layui-form-mid layui-word-aux name"></div>
			</div>
            <div class="layui-form-item">
                <label class="layui-form-label unitlabel">商品单位：</label>
                <div class="layui-form-mid layui-word-aux unit"></div>
            </div>
            <div class="layui-form-item pre_table">
                <label class="layui-form-label productSpecVoListlabel">商品原价格：</label>
                <div class="layui-input-block mytable">

                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">商品现价格：</label>
                <div class="layui-input-block modifytable">

                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">统计时间：</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" id="selectTime" placeholder="">
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn chartSearch">查询</button>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <div class="layui-input-inline">
                    <select name="labelName" lay-filter="labelName">
                        <option value="">默认商品价格</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <div class="layui-input-block">
                    <div id="main" style="width: 800px;height:600px;"></div>
                </div>
            </div>
		</form>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn sure">提交</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="window.history.back()">取消</button>
            </div>
        </div>
	</div>
</div>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="plugins/layui/layui.js"></script>
<script src="js/productLabelFormat.js"></script>
<script src="js/productDetail.js"></script>
<script src="js/echarts.common.min.js"></script>
<script>
	layui.config({
	    base: 'plugins/layui/modules/'
	}).use(['layer', 'form', 'http','laydate','table'], function () {
	    var layer = layui.layer,
	        http = layui.http,
	        form = layui.form,
			laydate = layui.laydate;

        //时间
        laydate.render({
            elem: '#selectTime'
            ,theme: '#fbaf7e'
            ,type: 'month'
        });
        // ------------------------ 回显信息 ------------------------

        var id = http.getPid('id');

        var specificationList = [];
        var specificationList1 = '';
        var productDetail,canteenLabelList

        // 列表查询所有食堂等级
        http.get('supplier/admin/label/listAll',{
            page: 1,
            limit: 10
        },function(res){
            if(res.code == 200){
                canteenLabelList = res.data
                
                var html = '<option value="">默认商品价格</option>';
                for (var i = 0; i < canteenLabelList.length; i++) {
                    html += '<option value="' + canteenLabelList[i].id + '">' + canteenLabelList[i].labelName + '单价</option>'
                }
                $('select[name=labelName]').html(html);
                form.render('select');
                getInfo()
            }else{
                layer.msg(res.msg)
            }
        })

        function getInfo(){
            http.get('supplier/admin/product/findById',{productId:id},function(res){
                var data = res.data;
                productDetail = JSON.stringify(res.data)
                $('.name').html(data.name);
                $('.unit').html(data.unitName)

                // 商品主图
                if(data.mainImage){
                    $('.mainImg').hide()
                    $('.showMImg').show().siblings('li').hide();
                    var imgId = http.getUUID();
                    var html = '<div id="div'+imgId+'" class="imgdiv" onmouseover="showOperation(\'span'+imgId+'\')" onmouseout="hideOperation(\'span'+imgId+'\')">'+
                                        '<img onurl="'+data.mainImage+'" src="'+(TUrl+data.mainImage)+'" id="proimg'+imgId+'">'+
                                    '</div>';

                    $('.showMImg').html(html);
                }
                form.render();

                    //规格
                specificationList = [];
                var s = data.productSpecVoList;
                for(var j=0;j<s.length;j++){
                    var p = {
                        name: s[j].specName
                    }
                    var p_enums = [];
                    for(var k=0;k<s[j].productSpecValueList.length;k++){
                        p_enums.push(s[j].productSpecValueList[k].specValue)
                    }
                    p.p_enums = p_enums;
                    specificationList.push(p)
                }
                getTable(data.goodVoList);// 回显商品现价格
                http.get('supplier/admin/product/lastProductPrice',{productId: id}, function(res){
                    if(res.data.length>0){
                        var obj = {}
                        for(var i=0;i<res.data.length;i++){
                            obj[res.data[i].goodId] = res.data[i]
                        }
                        getPreTable(data.goodVoList,obj) // 回显商品原价格
                        $('.pre_table').show()
                    }
                })
                specificationList1 = testProduct(specificationList);//调用product.js中方法
            })
        }
        // 回显商品原价格
        function getPreTable(goodVoList,obj){
            if(goodVoList.length>0){
                var tableH = '<table class="layui-table inputTable"><thead><tr>';

                for(var i=0;i<specificationList.length;i++){
                    tableH += '<th>'+specificationList[i].name+'</th>'
                }

                tableH += '<th><div><span>默认商品价格</span></div></th>';
                     
                // 食堂等级(2020/12/5新增)
                for(var g=0;g<canteenLabelList.length;g++){
                    tableH += '<th><div><span>'+canteenLabelList[g].labelName+'单价</span></div></th>'
                }

                tableH += '</tr></thead><tbody>'
                                          
                for(var j=0;j<goodVoList.length;j++){
                    tableH += '<tr>'
                    for(var k=0;k<goodVoList[j].goodSpecVoList.length;k++){
                        tableH += '<td>'+goodVoList[j].goodSpecVoList[k].specValue+'</td>';
                    }
                    tableH += '<td>'+obj[goodVoList[j].id].price+'</td>'
                     
                    // 食堂等级
                    var list = labelInfoWith(canteenLabelList, goodVoList[j].goodLabelPriceList) // 食堂等级列表对应价格(2020/12/8新增)
                    for (var g=0;g<list.length;g++) {
                        tableH += '<td>'+(list[g].goodPrice?list[g].goodPrice:obj[goodVoList[j].id].price)+'</td>'
                    }
                }     
        
                tableH += '</tbody></table>';

                $('.mytable').html(tableH)
            }
        }
        // 回显商品现价格
        function getTable(goodVoList){ 
            if(goodVoList.length>0){
                var tableM = '<table class="layui-table inputTable"><thead><tr>';

                for(var i=0;i<specificationList.length;i++){
                    tableM += '<th>'+specificationList[i].name+'</th>'
                }
                tableM += '<th>默认商品价格</th>'	

                // 食堂等级(2020/12/5新增)
                for(var g=0;g<canteenLabelList.length;g++){
                    tableM += '<th><div><span>'+canteenLabelList[g].labelName+'单价</span><input type="number" name="label'+canteenLabelList[g].id+'" autocomplete="off" class="layui-input"/></div></th>'
                }

                tableM += '</tr></thead><tbody>'

                for(var j=0;j<goodVoList.length;j++){
                    tableM += '<tr>';
                    for(var k=0;k<goodVoList[j].goodSpecVoList.length;k++){
                        tableM += '<td>'+goodVoList[j].goodSpecVoList[k].specValue+'</td>';
                    }

                    tableM += '<td><input type="number" name="price" autocomplete="off" class="layui-input" value="'+goodVoList[j].price+'"/></td>'

                    // 食堂等级
                    var list = labelInfoWith(canteenLabelList, goodVoList[j].goodLabelPriceList) // 食堂等级列表对应价格(2020/12/8新增)
                    for (var g=0;g<list.length;g++) {
                        tableM += '<td><input type="number" name="label'+list[g].id+'" autocomplete="off" class="layui-input" value="'+(list[g].goodPrice?list[g].goodPrice:goodVoList[j].price)+'"/></td>'
                    }
                }     
                tableM += '</tbody></table>'

                $('.modifytable').html(tableM)
            }
        }

        $(document).on("input",".modifytable th input", function () {//规格明细表格中的input监听
            // if($('th input[name=price]').val())
            //     $('td input[name=price]').val($('th input[name=price]').val());

            // 食堂等级(2020/12/5新增)
            for(var g=0;g<canteenLabelList.length;g++){
                if($('th input[name=label'+canteenLabelList[g].id+']').val())
                    $('td input[name=label'+canteenLabelList[g].id+']').val($('th input[name=label'+canteenLabelList[g].id+']').val());
            }
        });

        // 统计
        var myChart = echarts.init(document.getElementById('main'));
        // 当前的价格趋势数据
        var currentProductPriceData;
        chartFun()
        function chartFun(startTime,endTime){
            http.get('supplier/admin/product/listProductUpdatePriceRecord',{
                productId: id,
                startTime: startTime,
                endTime: endTime
            },function(res){
                if(res.code == 200){
                    currentProductPriceData = res.data;
                    var option = releaseEchartData(currentProductPriceData, null);
                    // console.log(option);
                    myChart.setOption(option);
                }else{
                    layer.msg(res.msg)
                }
            })

        }

        form.on('select(labelName)',function(data) {
            // console.log(data)
            var option = releaseEchartData(currentProductPriceData, data.value);
            myChart.setOption(option);
        })

        /**
         * 构造表格数据
         * @param respData 后端响应的数据 response.data
         * @param labelId 标签id 字符串 如果不传，就默认显示销售价的柱状图
         */
        function releaseEchartData(respData, labelId){
            if (respData){
                var legendData = []
                var xAxisData = []
                var seriesData = []
                for(var i=0;i<respData.length;i++){
                    legendData.push(respData[i].skuName)
                    var a = {
                        name: respData[i].skuName,
                        type: 'bar',
                        data: []
                    }
                    for(var k=0;k<respData[i].goodPriceWithTimeVoList.length;k++){
                        // 查找价格，如果传递了标签，就查找对应的标签的价格
                        var goodPriceWithTimeVo = respData[i].goodPriceWithTimeVoList[k];
                        var price = goodPriceWithTimeVo.price;
                        // 判断是否传递了标签
                        if (labelId != null && labelId != ''){
                            // 商品的标签价格列表
                            var goodLabelPriceList = goodPriceWithTimeVo.goodLabelPriceList;
                            if (goodLabelPriceList){
                                // 进行查找
                                for (var j = 0; j < goodLabelPriceList.length; j++) {
                                    var goodLabelPrice = goodLabelPriceList[j];
                                    if (goodLabelPrice.labelName == labelId){
                                        price = goodLabelPrice.goodPrice;
                                        break;
                                    }
                                }
                            }
                        }
                        a.data.push(price)
                    }
                    seriesData.push(a)
                }
                for(var j=0;j<respData[0].goodPriceWithTimeVoList.length;j++){
                    xAxisData.push(respData[0].goodPriceWithTimeVoList[j].time)
                }

                return  {
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        type: 'scroll',
                        top: 0,
                        data: legendData
                    },
                    grid: {
                        top: 100,//距离右边距
                    },
                    calculable: true,
                    dataZoom: [
                        {
                            type: 'slider',
                            show: true,
                        },
                    ],
                    xAxis: [
                        {
                            type: 'category',
                            data: xAxisData
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value'
                        }
                    ],
                    series: seriesData
                };
            }
            return null;
        }

        $('.chartSearch').click(function(){
            var time = $('#selectTime').val()
            if(time){
                var day = new Date(time.split('-')[0],time.split('-')[1],0);   //最后一个参数为0,意为获取2018年10月一共多少天
                var date = day.getDate()
                chartFun(time+'-1',time+'-'+date)
            }
        })


        // 提交
        $(".sure").click(function () {

            var goodState = true;
            var goodList = [];                                 //规格明细
            for(var x=0;x<specificationList1[0].length;x++){
                var pp = {
                    "goodImage": '',
                    "price":$('.modifytable td input[name=price]').eq(x).val(),
                    "stockCount": 99999,
                    "goodSpecParamsList":[],                    //商品的规格
					"goodLabelPriceList": [] // 食堂等级价格(2020/12/5新增)
                };

                if(!$('.modifytable td input[name=price]').eq(x).val() || $('.modifytable td input[name=price]').eq(x).val()==''){
                    layer.msg('默认商品价格不能为空');
                    goodState = false;
                    break;
                }
                for(var y=0;y<specificationList1.length;y++){
                    var e = {
                        specName: specificationList[y].name,
                        specValue: specificationList1[y][x]
                    }
                    pp.goodSpecParamsList.push(e);
                }

                // 食堂等级价格(2020/12/5新增)
                for(var g=0;g<canteenLabelList.length;g++){
                    // 食堂等级价格必填
                    if (!$('.modifytable td input[name=label'+canteenLabelList[g].id+']').val() || $('.modifytable td input[name=label'+canteenLabelList[g].id+']').val() == '') {
                        layer.msg(canteenLabelList[g].labelName+'单价不能为空');
                        goodState = false;
                        return;
                    }
                    pp.goodLabelPriceList.push({
                        labelName: canteenLabelList[g].id,
                        goodPrice: $('.modifytable td input[name=label'+canteenLabelList[g].id+']').val()
                    })
                }

                goodList.push(pp)
            }

            if(!goodState){
                return
            }
			if(typeof(productDetail)!="object"){
				productDetail = JSON.parse(productDetail)
			}
            var productSpecParamsList = []
            for(var i=0;i<productDetail.productSpecVoList.length;i++){
                var a ={
                    specName: productDetail.productSpecVoList[i].specName,
                    specValueList: []
                }
                for(var j=0;j<productDetail.productSpecVoList[i].productSpecValueList.length;j++){
                    var b ={
                        imageValue: '',
                        value: productDetail.productSpecVoList[i].productSpecValueList[j].specValue
                    }
                    a.specValueList.push(b)
                }
                productSpecParamsList.push(a)
            }

            var param = {
                id:id,
                name: productDetail.name,// 名称
                brand: productDetail.brand,// 商品品牌
                categoryId: productDetail.categoryId,//所属分类
                unit: productDetail.unit,// 单位
                searchKeyWord: productDetail.searchKeyWord, // 搜索关键字
                updateStatus: productDetail.updateStatus,// 是否可改单
                publicStatus: productDetail.publicStatus, // 是否公示
                quoteStatus: productDetail.quoteStatus, // 是否需报价
                productSpecParamsList: productSpecParamsList, //规格与规格值
                goodList:goodList, // 商品列表
                reportDueTime: productDetail.reportDueTime, // 检测报告到期时间
                mainImage: productDetail.mainImage, // 商品主图
                smallPic: productDetail.smallPic, // 商品图片
                content: productDetail.content, // 商品详情
                annexFiles: productDetail.annexFiles, // 附件
                shelfStatus: productDetail.shelfStatus,
            }
            // 报价
            http.postJSON('supplier/admin/product/quote',JSON.stringify(param),function(res){
                if(res.code == 200){
                    layer.msg('操作成功')
                    setTimeout(function(){
                        window.history.back()
                    },500)
                }else{
                    layer.msg(res.msg)
                }
            })
        })

    })

	//显示图片操作
	function showOperation(imgId){
		$('#'+imgId+'').show();
	}
	//隐藏图片操作
	function hideOperation(imgId){
		$('#'+imgId+'').hide();
	}
	//图片移除
	function deleteimg(imgId){
		$('#'+imgId+'').remove();
	}
</script>
</body>

</html>
